--
-- Author: yawei.zhu
-- Date: 2018-05-02 11:19:47
--
-- TaskModel
--
local RoadHeroProcess = import(".RoadHeroProcess")

local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ModelBase)

-- local arrPanelName = {L("主线任务"), L("目标任务"), L("每日任务"), L("赏金任务"), L("每周任务"), L("英雄之路")}
local arrPanelName = {L("task_main_desc"), L("task_branch_desc"), L("task_daily_desc"), L("task_gold_desc"), L("task_weekly_desc"), L("task_road_desc")}
local firstMenuNum = 3

function ClassRef:ctor(data)
    self.super.ctor(self, data)
end

function ClassRef:init()
	self._menuList = {}
	self._fameSubkeys = {}
end

function ClassRef:initModel()
	self:initFameSubKeys()
	self:initBountyTasks()
end

function ClassRef:initFameSubKeys()
	self._fameSubkeys = {}
	local subKeys = GD:queryAllFameSubKeys()
	if not subKeys then return end
	for k,v in pairs(subKeys) do
        if tonumber(v.showType) ~= 1 then
		    table.insert(self._fameSubkeys, v)
        end
	end
	table.sort(self._fameSubkeys, function(a,b) return tonumber(a.ID) < tonumber(b.ID) end)
end

function ClassRef:getFameSubKeyById(id)
	for i,v in ipairs(self._fameSubkeys) do
		if tonumber(v.ID) == tonumber(id) then
			return v
		end
	end
	return nil
end

-- 重新生成列表，因为tab的开启状态可能会改变，openView的时候调用
function ClassRef:getNewMenuList()
	self._menuList = {}
	local index = 0

	-- 主线任务默认开启
	local temp = {}
	index = index + 1
	temp.index = index
	temp.id = Constant.FUNC_TYPE_TASK
	temp.type = 0
	temp.name = arrPanelName[1]
	temp.subDatas = {}
	table.insert(self._menuList, temp)

	-- 判断支线任务是否开启
	local bOpen = UIHandler:isFunctionOpen(Constant.FUNC_TYPE_TASK_BRANCH)
	if bOpen then
		local branchTasks = UD:getAllBranchTasks()
		if #branchTasks > 0 then -- 有支线任务时，才显示页签
			local temp = {}
			index = index + 1
			temp.index = index
			temp.id = Constant.FUNC_TYPE_TASK_BRANCH
			temp.type = 1
			temp.name = arrPanelName[2]
			temp.subDatas = {}
			table.insert(self._menuList, temp)
		end
	end

	-- 判断每日任务是否开启
	--[[
	bOpen = UIHandler:isFunctionOpen(Constant.FUNC_TYPE_TASK_DAILY)
	if bOpen then
		local temp = {}
		index = index + 1
		temp.index = index
		temp.id = Constant.FUNC_TYPE_TASK_DAILY
		temp.type = 2
		temp.name = arrPanelName[3]
		temp.subDatas = {}
		table.insert(self._menuList, temp)
	end
	]]

	-- 判断赏金任务是否开启
	bOpen = UIHandler:isFunctionOpen(Constant.FUNC_TYPE_TASK_GOLD)
	if bOpen then
		local temp = {}
		index = index + 1
		temp.index = index
		temp.id = Constant.FUNC_TYPE_TASK_GOLD
		temp.type = 4
		temp.name = arrPanelName[4]
		temp.subDatas = {}

		for i, v in ipairs(self._fameSubkeys) do
            local fameIsOpen = GD:checkFameIsOpenBySubKey(tonumber(v.ID))
            if fameIsOpen then
			    local subTemp = {}
			    subTemp.id = i
			    subTemp.ID = v.ID
			    subTemp.name = L(v.belongMap)
			    table.insert(temp.subDatas, subTemp) -- 添加到赏金任务下面
            end
		end

		table.insert(self._menuList, temp)
	end

	-- 判断每周任务是否开启
	--[[
	bOpen = UIHandler:isFunctionOpen(Constant.FUNC_TYPE_TASK_WEEKLY)
	if bOpen then
		local temp = {}
		index = index + 1
		temp.index = index
		temp.id = Constant.FUNC_TYPE_TASK_WEEKLY
		temp.type = 3
		temp.name = arrPanelName[5]
		temp.subDatas = {}

		 table.insert(self._menuList, temp)
	end
	--]]

	-- 判断英雄之路是否开启 TODO
	bOpen = UIHandler:isFunctionOpen(Constant.FUNC_TYPE_TASK_ROADHERO)
	if bOpen then
		local temp = {}
		index = index + 1
		temp.index = index
		temp.id = Constant.FUNC_TYPE_TASK_ROADHERO
		temp.type = 100
		temp.name = arrPanelName[6]
		temp.subDatas = {}

		table.insert(self._menuList, temp)
	end

	return self._menuList
end

function ClassRef:getMenuList()
	return self._menuList
end

function ClassRef:getMenuDataByFuncId(funcId)
	local temp = nil
	for i, data in ipairs(self._menuList) do
		if data.id == funcId then
			return data
		end
	end 
	return nil
end

function ClassRef:getMainTaskData()
	local data = {}
	local task = UD:getTaskById(UD:getCurTaskId())
	if task and task:getConfig() then
		data.name = L(task:getConfig().name) or ""
		data.target = L(task:getConfig().target) or ""
		data.des = L(task:getConfig().content) or ""
		data.taskIcon = task:getConfig().taskIcon
		data.dropItems = TaskManager:getTaskDropItems(UD:getCurTaskId(),task:getConfig())
	end
	return data
end

function ClassRef:getTaskDigestsByTaskId(taskId)
	local digests = {}
	digests[1] = {}
	digests[1].digests = "" -- 默认有一章

	local tTasks = GD:queryTasks()
	for i,v in ipairs(tTasks) do
		if tonumber(v.type) == 0 and v.previousPlot ~= nil and tonumber(v.ID) <= tonumber(taskId) then
			local pArray = string.split(v.previousPlot,"|")
			if #pArray >= 2 then
				local groupId = tonumber(pArray[1])
				local s = tonumber(pArray[2])
				local digest = ""
				if s ~= 0 then
					digest = tostring(pArray[2])
				end

				if digests[groupId] == nil then
					digests[groupId] = {}
					digests[groupId].digests = ""
				elseif digests[groupId].digests ~= "" then
					digests[groupId].digests = digests[groupId].digests .. "\n" -- 每两个任务之间加换行
				end
				digests[groupId].digests = digests[groupId].digests .. L(digest)
			end
		end
	end

	return digests
end

function ClassRef:splitTaskDigests()
	local digestWords = {}
	local digests = self:getTaskDigestsByTaskId(UD:getCurTaskId())
	for k, v in ipairs(digests) do
		digestWords[k] = {}

		local page = 1
		local pos = 1
		local str = v.digests
		local len = string.len(str)

		-- TODO 换成string.split
		while(true) do
			local iBegin, iEnd = string.find(str, "###", pos)
			if iBegin then
				digestWords[k][page] = string.sub(str, pos, iBegin - 1)
				page = page + 1
				pos = iEnd + 1
			else
				if pos <= len then
					digestWords[k][page] = string.sub(str, pos)
				end
				break
			end
		end
	end

	return digestWords
end

function ClassRef:getBranchTasks()
	-- return UD:getTakenBranchTasks(true)
	return UD:getAllBranchTasks(true)
end

function ClassRef:getDailyTasks()
	local tasks = UD:getTotalDailyTasks()
	self._dailyTaskNumber = #tasks
	local totalTasks = {}
	local rewardedTasks = {}
	local finishedTasks = {}
	for i,v in ipairs(tasks) do
		v.dropItems = TaskManager:getTaskDropItems(v:getId())
		if v:isRewarded() then
			table.insert(rewardedTasks,v)
		elseif v:isFinished() then
			table.insert(finishedTasks,v)
		else
			table.insert(totalTasks,v)
		end

	end

	-- 按位置排序
	local function sortTask(a, b)
		return a.Pos < b.Pos
	end

	table.sort(rewardedTasks, sortTask)
	table.sort(finishedTasks, sortTask)
	table.sort(totalTasks, sortTask)

	for i,v in ipairs(finishedTasks) do
		table.insert(totalTasks,i,v)
	end
	local tLen = #totalTasks
	for i,v in ipairs(rewardedTasks) do
		table.insert(totalTasks,tLen + i,v)
	end

	return totalTasks
end

function ClassRef:getTotalDailyTaskNumber()
	return self._dailyTaskNumber or #UD:getTotalDailyTasks()
end

function ClassRef:getFinishedDailyTaskNumber()
	return #UD:getFinishedDailyTasks()
end

function ClassRef:getDailyTaskRewardProgress(needProgress)
	return TaskManager:getDailyTaskInfo():getTaskRewardProgress(needProgress)
end

function ClassRef:getDailyTaskRewards( needProgress, nowProgress )
	return TaskManager:getDailyTaskInfo():getTaskRewards( needProgress, nowProgress )
end

function ClassRef:getWeeklyTasks()
	local tasks = UD:getAllWeeklyTasks()
	self._weeklyTaskNumber = #tasks
	local finishTasks = {}
	local rewardTasks = {}
	local totalTasks = {}

	for _, task in ipairs(tasks) do
		if task:isRewarded() then
			table.insert(rewardTasks, task)
		elseif task:isFinished() then
			table.insert(finishTasks, task)
		else
			table.insert(totalTasks, task)
		end
	end

	for k, v in ipairs(finishTasks) do
		table.insert(totalTasks, k, v)
	end
	for k, v in ipairs(rewardTasks) do
		table.insert(totalTasks, v)
	end
	return totalTasks
end

function ClassRef:getTotalWeeklyTaskNumber()
	return self._weeklyTaskNumber or #UD:getAllWeeklyTasks()
end

function ClassRef:getFinishedWeeklyTaskNumber()
	return #UD:getFinishedWeeklyTasks()
end

function ClassRef:getWeeklyTaskRewardProgress(needProgress)
	return TaskManager:getWeeklyTaskInfo():getTaskRewardProgress(needProgress)
end

function ClassRef:getWeeklyTaskRewards( needProgress, nowProgress )
	return TaskManager:getWeeklyTaskInfo():getTaskRewards( needProgress, nowProgress )
end

function ClassRef:isNeedTrack(taskId)
	return TaskManager:isNeedTrack(taskId)
end

function ClassRef:initBountyTasks()
	self._bountyTasks = {}
	local tasks = UD:getTotalBountyTasks()
	for i,v in ipairs(tasks) do
		v.dropItems = TaskManager:getTaskDropItems(v:getId())
		local district = tonumber(v:getConfig().district)
		if district then
			self._bountyTasks[district] = (self._bountyTasks[district] == nil) and {} or self._bountyTasks[district]
			table.insert(self._bountyTasks[district],v)
		end
	end

	for k,v in pairs(self._bountyTasks) do
		table.sort(v, function(a,b) return a.Pos < b.Pos end)
	end
end

function ClassRef:getBountyTasks()
	return self._bountyTasks
end

function ClassRef:getBountyTaskInfo()
	return TaskManager:getBountyTaskInfo()
end

function ClassRef:getBountyTaskRefresh(district, pos)
	return TaskManager:getBountyTaskInfo():getTaskRefresh(district,pos)
end

function ClassRef:isBountyTaskFinished()
	return TaskManager:isBountyTaskFinished()
end

function ClassRef:setSelFameSubId(fameSubId)
	self._selFameSubId = fameSubId
end

function ClassRef:getSelFameSubId()
	return self._selFameSubId
end

function ClassRef:setRefreshIndex(index)
	self._refreshFameSubId = self._selFameSubId
	self._refreshIndex = index
end

function ClassRef:getRefreshIndex()
	return self._selFameSubId, self._refreshIndex
end

function ClassRef:setNewTaskId(taskId)
	self._newTaskId = taskId
end

function ClassRef:getNewTaskId()
	return self._newTaskId
end

function ClassRef:getBountyTaskProgressBySubkey(subKey)
	local iTotalCount = GD:getFameTotalCount(subKey)
	local iAlreadyCount = UD:getFameCountBySubKey(subKey)

	local percent = self:getPreciseDecimal(iAlreadyCount / iTotalCount * 100, 2)
	local percentStr = percent .. "%"

	return percent,percentStr
end

function ClassRef:getPreciseDecimal(number, n)
    if type(number) ~= "number" then
        return number
    end
    n = n or 0
    n = math.floor(n)
    local fmt = '%.' .. n .. 'f'
    local nRet = tonumber(string.format(fmt, number))
    return nRet
end

function ClassRef:getBountyTaskFameBySubkey(subKey)
	local famesC = {}
	local fames = GD:queryFameBySubKey(subKey)
	for k,v in pairs(fames) do
		local fameId = tonumber(v.ID)
		local level,exp,totalExp,levelName,fameName = GD:getFameNameLevelExp(fameId)
		local fameStr
		if tonumber(totalExp) == 0 then
			fameStr = fameName .. " " .. levelName .. " (MAX)"
		else
			fameStr = fameName .. " " .. levelName .. " (" .. exp .. "/" .. totalExp .. ")"
		end
		local famePercent = exp / totalExp * 100
		table.insert(famesC,{fameStr = fameStr,famePercent = famePercent})
	end
	return famesC
end

-- 获取 英雄之路 信息
function ClassRef:getRoadOfHeroProcess()
	return self._roadHeroProcess
end

-- 更新英雄之路红点
function ClassRef:updateRoadHeroRedPoint()
	if self._roadHeroProcess:checkHasAward() then
		UD.badge:setNum(Constant.FUNC_TYPE_TASK, 1)
	end
end

------------------------ receive ------------------------
function ClassRef:onRoadOfHeroProcess(ret)
	self._roadHeroProcess = RoadHeroProcess.new(ret)
	app:sendMsg("TaskController", "updateRoadHeroInfo", self._roadHeroProcess)
end

-- 英雄之路，通关某个节点结算
function ClassRef:onFinishRoadOfHeroBattle(msg)
	dump(msg)
	if not self._roadHeroProcess then return end
	if not msg then return end

	if msg.Won and msg.Level > self._roadHeroProcess.level or (msg.Level == self._roadHeroProcess.level and msg.Step > self._roadHeroProcess.step) then
		self._roadHeroProcess.level = msg.Level
		self._roadHeroProcess.step = msg.Step
		-- 只在进度更新的时候去更新红点
		self:updateRoadHeroRedPoint()
	end

	app:sendMsg("TaskController", "openView", {Constant.FUNC_TYPE_TASK_ROADHERO})
end

------------------------ request ------------------------
-- 请求英雄之路进度
function ClassRef:reqRoadOfHeroProcess()

	if false then
		local ret = {}
		ret.Level = 2
		ret.Step = 3
		local arr = {}
		table.insert(arr, false)
		table.insert(arr, true)
		table.insert(arr, false)
		table.insert(arr, false)
		ret.BoxStatus = arr 
		self:onRoadOfHeroProcess(ret)
		return
	end

	app.session:request("pb_roadOfHero.C2S_RoadOfHeroProcess", {})
end

-- 英雄之路 请求开箱子
function ClassRef:reqRoadOfHeroOpenBox(level)
	print("reqRoadOfHeroOpenBox, level = ", level)
	app.session:request("pb_roadOfHero.C2S_RoadOfHeroOpenBox", {Idx = level}, function(msg)
		if msg.OK then
			print("road hero open box success.")
			-- 设置对应层级上的宝箱标记
			self._roadHeroProcess.boxStatus[level] = true
			app:sendMsg("TaskController", "updateRoadHeroInfo", self._roadHeroProcess)
		else
			print("road hero open box fail!!!")
		end
	end)
end

return ClassRef
